SpringBoot官方文档翻译(十七):Spring Beans和依赖注入

17. Spring Beans and Dependency Injection(Spring Beans和依赖注入)

1
2
3
4
5
You are free to use any of the standard Spring Framework     
techniques to define your beans and their injected dependencies.
For simplicity, we often find that using @ComponentScan 
(to find your beans) and using @Autowired (to do constructor
injection) works well.

您可以自由的使用Spring框架标注的一些技术和注解来定义您的注入依赖关系。打个比方,我们经常使用
@ComponentScan(去查找您的beans),用@Autowired(去做构造注入)。

1
2
3
4
5
If you structure your code as suggested above (locating your     
application class in a root package), you can add @ComponentScan 
without any arguments. All of your application components
(@Component, @Service, @Repository, @Controller etc.) are
automatically registered as Spring Beans.

如果您按照以上的建议构造您的代码结构(将您的主应用类放在根包下面),您可以增加@ComponentScan注解而不需要任何参数。您所有的应用组件(@Component, @Service, @Repository, @Controller 等等)都将被自动注册为Spring Beans。

1
2
The following example shows a @Service Bean that uses     
constructor injection to obtain a required RiskAssessor bean:

接下去的例子展示了@Service使用构造注入去获得必要的RiskAssessor bean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DatabaseAccountService implements AccountService {

private final RiskAssessor riskAssessor;

@Autowired
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}

// ...

}

1
2
If a bean has one constructor, you can omit the @Autowired,     
as shown in the following example:

如果一个bean有一个构造函数,您可以省略@Autowired注解,如下例子:

1
2
3
4
5
6
7
8
9
10
11
12
@Service
public class DatabaseAccountService implements AccountService {

private final RiskAssessor riskAssessor;

public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}

// ...

}

1
2
3
Notice how using constructor injection lets the riskAssessor     
field be marked as final, indicating that it cannot be
subsequently changed.

注意介绍如何使用构造注入使riskAssessor字段被标记为final,表明它不可以随后改变。

分享到